package android.tusnotas.connector.webcampus;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;

import android.tusnotas.connector.TusNotasCaller;
import android.tusnotas.connector.TusNotasHttpClient;
import android.tusnotas.core.GradeAnalyserStatuses;
import android.tusnotas.exception.RemoteReadingException;
import android.tusnotas.util.Devel;
import android.tusnotas.util.StringConverter;
import android.util.Log;

public class WebCampusCaller extends TusNotasCaller {
	
	private DefaultHttpClient client;
	
	private DefaultHttpClient prepareHttpClient(){

		TusNotasHttpClient httpClient = TusNotasHttpClient.getWebCampusHttpClient();
		return httpClient;
	}

	private void login() throws RemoteReadingException{
		
		Integer connectionStatus = GradeAnalyserStatuses.NO_FAILURE; 
		RemoteReadingException rwce = null;
		try {
			client = prepareHttpClient();
			HttpPost post = new HttpPost(WebCampusURLs.LOGIN);
			post.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
			post.setEntity(new UrlEncodedFormEntity(new WebCampusFiller().getPairs()));
			HttpResponse httpResponse = client.execute(post);
			Integer statusCode = httpResponse.getStatusLine().getStatusCode();
			String location = httpResponse.getHeaders("Location")[0].getValue();
			if (WebCampusURLs.LOGIN_URI.equalsIgnoreCase(location)){
				statusCode = 0;
			}
			
			switch (statusCode) {
			case -1:
				connectionStatus = GradeAnalyserStatuses.NOT_POSSIBLE_TO_CONNECT;
				break;
			case 0:
				connectionStatus = GradeAnalyserStatuses.WRONG_USER_OR_PASS;
				break;
			default:

				cookie= httpResponse.getHeaders("Set-Cookie")[0].getValue().split(";")[0];
				if (Devel.callerDevel || Devel.fullDevel){
					Log.w(this.getClass().getName(), "Log in to WC OK.");
				}
				return;
			}
		}
		catch( UnsupportedEncodingException ueException ) {
			connectionStatus = GradeAnalyserStatuses.WEIRD_FAILURE;
		}
		catch (IOException ioException) {
			connectionStatus = GradeAnalyserStatuses.NOT_POSSIBLE_TO_CONNECT;
		}
		catch (Exception e) {
			connectionStatus = GradeAnalyserStatuses.WEIRD_FAILURE;
		}
		if (Devel.callerDevel || Devel.fullDevel){
			Log.w(this.getClass().getName(), "Log in to WC NOT OK.");
		}
		rwce = new RemoteReadingException();
		rwce.setErrorCode(connectionStatus);
		throw rwce;
	}
	
	private String askForHome() throws RemoteReadingException{
		
		Integer connectionStatus = GradeAnalyserStatuses.NO_FAILURE; 
		RemoteReadingException rwce = null;
		Log.w(this.getClass().getName(), "starting...");

		try {
			client = prepareHttpClient();
			
			HttpUriRequest get = new HttpGet(WebCampusURLs.HOME);
			get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
			get.addHeader("Cookie", cookie);
			
			HttpResponse httpResponse = client.execute(get);
			
			if (httpResponse.getStatusLine().getStatusCode() != -1 ) {
				
				Header[] locationHeaders = httpResponse.getHeaders("Location");
				if (locationHeaders != null && locationHeaders.length > 0){
					if (WebCampusURLs.LOGIN_URI.equals(locationHeaders[0].getValue().trim())){
						login();
						client = prepareHttpClient();
						get.removeHeaders("Cookie");
						get.addHeader("Cookie", cookie);
						httpResponse = client.execute(get);
					}
				}
				if (Devel.callerDevel || Devel.fullDevel){
					Log.w(this.getClass().getName(), "Getting WC Home OK");
				}
				return StringConverter.slurp(httpResponse.getEntity().getContent());
			}
			return "";
		}
		
		catch (IOException ioe) {
			connectionStatus = GradeAnalyserStatuses.NOT_POSSIBLE_TO_CONNECT;
		}
		catch (Exception e) {
			connectionStatus = GradeAnalyserStatuses.WEIRD_FAILURE;
		}
		if (Devel.callerDevel || Devel.fullDevel){
			Log.w(this.getClass().getName(), "Getting WC Home NOT OK");
		}
		rwce = new RemoteReadingException();
		rwce.setErrorCode(connectionStatus);
		throw rwce;
	}
	
	/* (non-Javadoc)
	 * @see android.tusnotas.connector.Caller#execute()
	 */
	@Override
	public String execute() throws RemoteReadingException{
		if (cookie == null || "".equals(cookie.trim())){
			login();
		}
		
		String HTML=askForHome();
				
		if (HTML != null && !HTML.equals("")){
			return HTML;
		}
		
		RemoteReadingException rwce = new RemoteReadingException();
		rwce.setErrorCode(GradeAnalyserStatuses.WEIRD_FAILURE);
		throw rwce;
	}

	@Override
	public void setForGrades() {
	}

	@Override
	public void SetForMoreInfoCouse(String aulaID) {
	}

}
